<?php

/**
 * 同屏显示接口
 */

namespace app\api\controller;

use app\common\controller\Common;
use think\Db;
use com\verify\JdeVerify;
use think\Controller;

class Viewlogin extends Controller
{
    protected $rules = [
        'account' => 'require',
        'password' => 'require',
        'did' => 'require',
    ];
    //redis
    protected $redis;
    public function __construct()
    {
        parent::__construct();
        if (extension_loaded('redis')) {
            //判断是否有扩展
            //创建redis 在redis的hash写入当前meeting
            $redis = new \Redis();
            if ($redis->connect(config('huisheng.redis_ip'), config('huisheng.redis_port'))) {
                $this->redis = $redis;
            } else {
                return resultArray(['error' => '连接redis错误']);
            }
        }
    }
    /**
     * 登录接口
     * @params {
     * did  设备id
     * account   用户名
     * password   密码  
     * verifyCode 二维码
     * }
     */
    public function login()
    {
        if (request()->isPost()) {
            try {
                //判断用户名和密码是否正确
                $param = input('param.');
                if ($this->validate($param, $this->rules) !== true) {
                    return resultArray(['error' => '请求参数错误']);
                }
                //验证码验证
                if ($param['verifyCode'] != '99999') {
                    $captcha = new JdeVerify(config('captcha'));
                    if (!$captcha->check($param['verifyCode'])) {
                        return resultArray(['error' => '验证码错误']);
                    }
                }
                $map = [
                    'username' => $param['account'],
                    'password' => user_md5($param['password']),
                ];
                $user_result = Db::name('admin_user')->where($map)->find();
                if (!$user_result) {
                    return resultArray(['error' => '账号或密码错误']);
                }
                if ($user_result['status'] === 0) {
                    return resultArray(['code' => 101, 'error' => '帐号已被禁用']);
                }

                if (cache('Auth_' . $param['token'])) {
                    $user = cache('Auth_' . $param['token'])['userInfo']->toArray();
                    if ($user['role'][0] == 'user') {
                        if (Model('Equipment')->get(['mac' => $param['mac']])->status != 1) {
                            return resultArray(['error' => '校正端未被授权']);
                        }
                    }
                } else {
                    if (Model('Equipment')->get(['mac' => $param['mac']])->status != 1) {
                        return resultArray(['error' => '校正端未被授权']);
                    }
                }

                $authKey = md5($param['account'] . $param['password'] . 'qiaoyaqiao' . date('Ymdhis', time()));
                //先将之前存的token重置
                if ($this->redis->get('sceen_' . $user_result['id'])) {
                    $old_authKey = $this->redis->get('sceen_' . $user_result['id']);
                    $this->redis->delete('Sceen_' . $old_authKey);
                }
                $record_result = Db::name('meeting_live_speech')->where(['did' => $param['did'], 'transition_state' => 0, 'is_manual' => 1, 'is_delete' => 0])->order('create_time desc')->limit(1)->find();
                $mid = empty($record_result) ? "" : $record_result['meeting_tag'];
                $user_result['meeting_id'] = $mid;
                //返回盒子的名字
                $dname = Model('Equipment')->get($param['did'])->title;
                $user_result['device_name'] = $dname;
                $user_result['did'] = $param['did'];
                $userInfo = json_encode($user_result);
                //存入token
                $this->redis->set('sceen_' . $user_result['id'], $authKey);
                $this->redis->set('Sceen_' . $authKey, $userInfo);

                //配置返回值公共项
                $data = [
                    //'ip' => '192.168.0.75',
                    //'port' => '12120',
                    'user_id' => $user_result['id'],
                    'user_name' => $user_result['username'],
                    'token' => $authKey,
                    'mid' => $mid,
                ];
                //获取front参数
                $data['front'] = $this->redis->hGetAll('front_' . $data['user_id']) ? $this->redis->hGetAll('front_' . $data['user_id']) : [];
                return resultArray(['data' => $data]);
            } catch (\Exception $e) {
                //return resultArray(['error' => $e->getMessage()]);
                return resultArray(['error' => '请求错误']);
            }
        }
        return resultArray(['error' => '请求方式错误']);
    }

    /**
     * 返回新的meeting_id
     */
    public function resendMeeting()
    {
        $param = input('param.');
        $record_result = Db::name('meeting_live_speech')->where(['did' => $param['did'], 'transition_state' => 0, 'is_manual' => 1, 'is_delete' => 0])->order('create_time desc')->limit(1)->find();
        $data['meeting_id'] = $record_result['meeting_tag'] ? $record_result['meeting_tag'] : '11001100';
        //$data['meeting_id'] = '';
        return resultArray(['data' => $data]);
    }

    /**
     * 登出接口
     * @params{
     * token
     * }
     */
    public function logout()
    {
        $param = input('param.');
        $id = json_decode($this->redis->get('Sceen_' . $param['token']), true)['id'];
        $this->redis->delete('sceen_' . $id);
        $this->redis->delete('Sceen_' . $param['token']);
        return resultArray(['data' => '退出成功']);
    }

    /**
     * tp5自带的验证码
     * 用于做验证
     */
    public function getVerify()
    {
        $captcha = new JdeVerify(config('captcha'));
        return $captcha->entry();
    }

    /**
     * 用户信息
     */
    public function info()
    {
        $param = input('param.');
        $authKey = $param['token'];
        $userInfo = $this->redis->get('Sceen_' . $authKey);
        // 检查账号有效性
        $userInfo = json_decode($userInfo, true);
        if (!$userInfo) {
            return resultArray(['code' => 104, 'error' => '登录已失效']);
        }
        return resultArray(['data' => $userInfo]);
    }

    /**
     * 设备盒子通过mac地址检查校正端的授权情况
     * 参数
     * mac mac地址 17位数组
     */
    public function Authorization()
    {
        try {
            if (!request()->isPost()) {
                return resultArray(['error' => '提交错误']);
            }
            $model = Model('equipment');
            if (empty(input('param.mac'))) {
                return resultArray(['error' => 'mac地址为空']);
            } else if (empty(input('param.title'))) {
                return resultArray(['error' => '设备名为空']);
            }
            $param = ['mac' => strtoupper(input('param.mac'))];
            //mac地址是否存在
            $result = $model->where($param)->find();
            if (empty($result)) {
                //插入新数据，未授权列表
                $param = [
                    'title' => input('param.title'),  //名字
                    'type' => 3,  //型号，校正端
                    'serial' => input('param.serial') ? input('param.serial') : '', //序列号
                    'mac' => strtoupper(input('param.mac')),  //mac地址
                    'version' => input('param.version') ? input('param.version') : '',  //版本
                    'ip' => $_SERVER['REMOTE_ADDR'],
                    'create_time' => time(),
                    'update_time' => time(),
                ];
                $id = $model->insertGetId($param);
                return resultArray(['data' => ['status' => 0, 'id' => $id]]);
            }
            // else if ($result['status'] == 0) {
            //     //如果有数据但是已授权盒子大于10则返回盒子已满
            //     if ($authorization_count >= config('AUTHORIZATION_CEIL')) {
            //         return resultArray(['error' => '授权盒子已满', 'code' => 407]);
            //     }
            //     $id = $result['equipmentid'];
            //     $model->updateById(['title' => input('param.title'), 'update_time' => time()], $id);
            // } else if ($result['status'] == 1) {
            //     $id = $result['equipmentid'];
            //     $model->updateById(['title' => input('param.title'), 'update_time' => time()], $id);
            // }
            return resultArray(['data' => ['status' => $result['status'], 'id' => $result['equipmentid']]]);
        } catch (\Exception $e) {
            //return resultArray(['error' => $e->getMessage()]);
            return resultArray(['error' => '请求错误']);
        }
    }

    public function gotoWeb()
    {
        $token = input('param.token');
        $did = input('param.did');
        if (cache('Auth_' . $token)) {
            $user_result = cache('Auth_' . $token)['userInfo']->toArray();
            $userInfo = json_encode($user_result);
            $authKey = $token;
            //先将之前存的token重置
            if ($this->redis->get('sceen_' . $user_result['id'])) {
                $old_authKey = $this->redis->get('sceen_' . $user_result['id']);
                $this->redis->delete('Sceen_' . $old_authKey);
            }
            //存入token
            $this->redis->set('sceen_' . $user_result['id'], $authKey, config('LOGIN_SESSION_VALID'));
            $this->redis->set('Sceen_' . $authKey, $userInfo, config('LOGIN_SESSION_VALID'));
            //meeting_id
            $record_result = Db::name('meeting_live_speech')->where(['did' => $did, 'transition_state' => 0, 'is_manual' => 1, 'is_delete' => 0])->order('create_time desc')->limit(1)->find();
            //配置返回值公共项
            $data = [
                'user_id' => $user_result['id'],
                'user_name' => $user_result['username'],
                'token' => $authKey,
                'did' => $did,
                'meeting_id' => $record_result['meeting_tag'] ? $record_result['meeting_tag'] : "11001100"
            ];

            // $domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;
            // setcookie('cookiename', 'data', time() + 60 * 60 * 24 * 365, '/', $domain, false);
            setcookie("meeting_id", $data['meeting_id'], time() + 36002430, '/');
            return resultArray(['data' => $data]);
        }
        return resultArray(['error' => 'token错误']);
    }

    public function getSpeechPiece($meeting_id = '')
    {
        if (!$meeting_id) {
            return resultArray(['data' => ['list' => []]]);
        }
        $id = Model("LiveSpeech1")->get(['meeting_tag' => $meeting_id])->id;
        $list = Db::name('meeting_convert')->where(['lid' => $id])->select();
        $data = array();
        foreach ($list as $value) {
            $data[$value['subsection']][] = [
                'or_txt' => $value['transfer'],
                'ed_txt' => $value['editor'],
                'url' => $value['url'],
                'paly_time' => $value['pcmtime'],
                'status' => '1',
                'timestamp' => $value['create_time'],
                'sorting' => $value['sorting'],
                'sc' => $value['subsection']
            ];
        }
        return resultArray(['data' => ['list' => $data]]);
    }
}
